package com.autoagent.ai_live_master.webSocket.converter;

import com.autoagent.ai_live_master.webSocket.model.*;
import com.autoagent.ai_live_master.webSocket.vo.*;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.util.ArrayList;

@Component
public class MessageConverter {

    // 将LiveMessage转换为统一格式的MemberJoinMessage
    public RealTimeBulletScreenMessage convertToUnifiedMemberJoinMessage(LiveMessage liveMessage) {
        if (liveMessage == null || !"WebcastMemberMessage".equals(liveMessage.getMethod())) {
            return null;
        }

        // 创建弹幕项
        RealTimeBulletScreenMessage.BulletScreenItem item = new RealTimeBulletScreenMessage.BulletScreenItem();
        item.setType("memberJoin");
        item.setComment(liveMessage.getContent());
        
        // 设置用户信息
        if (liveMessage.getUser() != null) {
            // 使用统一的用户信息转换方法
            UserProfile userProfile = convertToUserProfile(liveMessage.getUser());
            setUserProfileToItem(item, userProfile);
        }
        
        // 设置在线观看数
        if (liveMessage.getRoom() != null && liveMessage.getRoom().getAudienceCount() != null) {
            try {
                if (liveMessage.getRoom().getAudienceCount() instanceof Integer) {
                    item.setAudienceCount((Integer) liveMessage.getRoom().getAudienceCount());
                } else if (liveMessage.getRoom().getAudienceCount() instanceof Long) {
                    item.setAudienceCount(((Long) liveMessage.getRoom().getAudienceCount()).intValue());
                } else if (liveMessage.getRoom().getAudienceCount() instanceof String) {
                    item.setAudienceCount(Integer.parseInt((String) liveMessage.getRoom().getAudienceCount()));
                }
            } catch (Exception e) {
                item.setAudienceCount(null);
            }
        }

        // 创建统一格式消息
        RealTimeBulletScreenMessage realTimeBulletScreenMessage = new RealTimeBulletScreenMessage();
        realTimeBulletScreenMessage.setValue(Collections.singletonList(item));
        realTimeBulletScreenMessage.setId(liveMessage.getId());

        return realTimeBulletScreenMessage;
    }

    public RealTimeBulletScreenMessage convertToUnifiedChatMessage(LiveMessage liveMessage) {
        if (liveMessage == null || !"WebcastChatMessage".equals(liveMessage.getMethod())) {
            return null;
        }

        // 创建弹幕项
        RealTimeBulletScreenMessage.BulletScreenItem item = new RealTimeBulletScreenMessage.BulletScreenItem();
        item.setType("chat");
        item.setComment(liveMessage.getContent());
        
        // 设置用户信息
        if (liveMessage.getUser() != null) {
            // 使用统一的用户信息转换方法
            UserProfile userProfile = convertToUserProfile(liveMessage.getUser());
            setUserProfileToItem(item, userProfile);
        }

        // 创建统一格式消息
        RealTimeBulletScreenMessage realTimeBulletScreenMessage = new RealTimeBulletScreenMessage();
        realTimeBulletScreenMessage.setValue(Collections.singletonList(item));
        realTimeBulletScreenMessage.setId(liveMessage.getId());

        return realTimeBulletScreenMessage;
    }

    public RealTimeBulletScreenMessage convertToUnifiedGiftMessage(LiveMessage liveMessage) {
        if (liveMessage == null || !"WebcastGiftMessage".equals(liveMessage.getMethod())) {
            return null;
        }

        // 创建弹幕项
        RealTimeBulletScreenMessage.BulletScreenItem item = new RealTimeBulletScreenMessage.BulletScreenItem();
        item.setType("gift");
        
        // 设置用户信息
        if (liveMessage.getUser() != null) {
            // 使用统一的用户信息转换方法
            UserProfile userProfile = convertToUserProfile(liveMessage.getUser());
            setUserProfileToItem(item, userProfile);
        }

        // 设置礼物信息
        if (liveMessage.getGift() != null) {
            item.setGiftId(liveMessage.getGift().getId());
            item.setGiftName(liveMessage.getGift().getName());
            item.setGiftImage(liveMessage.getGift().getIcon());
            item.setGiftCount(liveMessage.getGift().getCount() instanceof Integer ?
                    (Integer) liveMessage.getGift().getCount() : 1);
        }

        // 创建统一格式消息
        RealTimeBulletScreenMessage realTimeBulletScreenMessage = new RealTimeBulletScreenMessage();
        realTimeBulletScreenMessage.setValue(Collections.singletonList(item));
        realTimeBulletScreenMessage.setId(liveMessage.getId());

        return realTimeBulletScreenMessage;
    }

    public RealTimeBulletScreenMessage convertToUnifiedLikeMessage(LiveMessage liveMessage) {
        if (liveMessage == null || !"WebcastLikeMessage".equals(liveMessage.getMethod())) {
            return null;
        }
    
        // 创建弹幕项
        RealTimeBulletScreenMessage.BulletScreenItem item = new RealTimeBulletScreenMessage.BulletScreenItem();
        item.setType("like");
        
        // 设置点赞内容
        String content = liveMessage.getContent();
        if (content == null || content.isEmpty()) {
            content = "为主播点赞了";
        }
        item.setComment(content);
        
        // 设置用户信息
        if (liveMessage.getUser() != null) {
            // 使用统一的用户信息转换方法
            UserProfile userProfile = convertToUserProfile(liveMessage.getUser());
            setUserProfileToItem(item, userProfile);
        }
        
        // 设置房间点赞总数
        if (liveMessage.getRoom() != null && liveMessage.getRoom().getLikeCount() != null) {
            try {
                if (liveMessage.getRoom().getLikeCount() instanceof Integer) {
                    item.setRoomLikeCount((Integer) liveMessage.getRoom().getLikeCount());
                } else if (liveMessage.getRoom().getLikeCount() instanceof Long) {
                    item.setRoomLikeCount(((Long) liveMessage.getRoom().getLikeCount()).intValue());
                } else if (liveMessage.getRoom().getLikeCount() instanceof String) {
                    item.setRoomLikeCount(Integer.parseInt((String) liveMessage.getRoom().getLikeCount()));
                }
            } catch (Exception e) {
                item.setRoomLikeCount(null);
            }
        }

        // 创建统一格式消息
        RealTimeBulletScreenMessage realTimeBulletScreenMessage = new RealTimeBulletScreenMessage();
        realTimeBulletScreenMessage.setValue(Collections.singletonList(item));
        realTimeBulletScreenMessage.setId(liveMessage.getId());

        return realTimeBulletScreenMessage;
    }

    public RealTimeBulletScreenMessage convertToUnifiedConnectMessage(LiveMessage liveMessage) {
        if (liveMessage == null || !"WebcastConnectMessage".equals(liveMessage.getMethod())) {
            return null;
        }

        // 创建弹幕项
        RealTimeBulletScreenMessage.BulletScreenItem item = new RealTimeBulletScreenMessage.BulletScreenItem();
        item.setType("connect");
        
        // 设置连接内容
        String content = liveMessage.getContent();
        if (content == null || content.isEmpty()) {
            content = "连接成功";
        }
        item.setComment(content);
        
        // 创建统一格式消息
        RealTimeBulletScreenMessage realTimeBulletScreenMessage = new RealTimeBulletScreenMessage();
        realTimeBulletScreenMessage.setValue(Collections.singletonList(item));
        realTimeBulletScreenMessage.setId(liveMessage.getId());
        
        return realTimeBulletScreenMessage;
    }

    public RealTimeBulletScreenMessage convertToUnifiedSocialMessage(LiveMessage liveMessage) {
        if (liveMessage == null || !"WebcastSocialMessage".equals(liveMessage.getMethod())) {
            return null;
        }

        // 创建弹幕项
        RealTimeBulletScreenMessage.BulletScreenItem item = new RealTimeBulletScreenMessage.BulletScreenItem();
        item.setType("social");
        
        // 设置用户信息
        if (liveMessage.getUser() != null) {
            // 使用统一的用户信息转换方法
            UserProfile userProfile = convertToUserProfile(liveMessage.getUser());
            setUserProfileToItem(item, userProfile);
        }
        
        // 设置社交消息内容
        String content = liveMessage.getContent();
        if (content == null || content.isEmpty()) {
            content = "关注了主播";
        }
        item.setComment(content);
        
        // 设置总关注人数
        if (liveMessage.getRoom() != null && liveMessage.getRoom().getFollowCount() != null) {
            try {
                if (liveMessage.getRoom().getFollowCount() instanceof Integer) {
                    item.setFollowCount((Integer) liveMessage.getRoom().getFollowCount());
                } else if (liveMessage.getRoom().getFollowCount() instanceof Long) {
                    item.setFollowCount(((Long) liveMessage.getRoom().getFollowCount()).intValue());
                } else if (liveMessage.getRoom().getFollowCount() instanceof String) {
                    item.setFollowCount(Integer.parseInt((String) liveMessage.getRoom().getFollowCount()));
                }
            } catch (Exception e) {
                item.setFollowCount(null);
            }
        }

        // 创建统一格式消息
        RealTimeBulletScreenMessage realTimeBulletScreenMessage = new RealTimeBulletScreenMessage();
        realTimeBulletScreenMessage.setValue(Collections.singletonList(item));
        realTimeBulletScreenMessage.setId(liveMessage.getId());

        return realTimeBulletScreenMessage;
    }

    public RealTimeBulletScreenMessage convertToUnifiedRoomUserSeqMessage(LiveMessage liveMessage) {
        if (liveMessage == null || !"WebcastRoomUserSeqMessage".equals(liveMessage.getMethod())) {
            return null;
        }

        // 创建弹幕项
        RealTimeBulletScreenMessage.BulletScreenItem item = new RealTimeBulletScreenMessage.BulletScreenItem();
        item.setType("roomUserSeq");
        
        // 设置在线观众数
        if (liveMessage.getRoom() != null && liveMessage.getRoom().getAudienceCount() != null) {
            try {
                if (liveMessage.getRoom().getAudienceCount() instanceof Integer) {
                    item.setAudienceCount((Integer) liveMessage.getRoom().getAudienceCount());
                } else if (liveMessage.getRoom().getAudienceCount() instanceof Long) {
                    item.setAudienceCount(((Long) liveMessage.getRoom().getAudienceCount()).intValue());
                } else if (liveMessage.getRoom().getAudienceCount() instanceof String) {
                    item.setAudienceCount(Integer.parseInt((String) liveMessage.getRoom().getAudienceCount()));
                }
            } catch (Exception e) {
                item.setAudienceCount(null);
            }
        }
        
        // 设置累计观看人数
        if (liveMessage.getRoom() != null && liveMessage.getRoom().getTotalUserCount() != null) {
            try {
                if (liveMessage.getRoom().getTotalUserCount() instanceof Integer) {
                    item.setTotalUserCount((Integer) liveMessage.getRoom().getTotalUserCount());
                } else if (liveMessage.getRoom().getTotalUserCount() instanceof Long) {
                    item.setTotalUserCount(((Long) liveMessage.getRoom().getTotalUserCount()).intValue());
                } else if (liveMessage.getRoom().getTotalUserCount() instanceof String) {
                    item.setTotalUserCount(Integer.parseInt((String) liveMessage.getRoom().getTotalUserCount()));
                }
            } catch (Exception e) {
                item.setTotalUserCount(null);
            }
        }
        
        // 设置排行榜信息
        if (liveMessage.getRank() != null && !liveMessage.getRank().isEmpty()) {
            List<RealTimeBulletScreenMessage.RankItem> rankItems = getRankItems(liveMessage);
            item.setRank(rankItems);
        }

        // 创建统一格式消息
        RealTimeBulletScreenMessage realTimeBulletScreenMessage = new RealTimeBulletScreenMessage();
        realTimeBulletScreenMessage.setValue(Collections.singletonList(item));
        realTimeBulletScreenMessage.setId(liveMessage.getId());

        return realTimeBulletScreenMessage;
    }

    private List<RealTimeBulletScreenMessage.RankItem> getRankItems(LiveMessage liveMessage) {
        List<RealTimeBulletScreenMessage.RankItem> rankItems = new ArrayList<>();
        for (LiveMessage.LiveRankItem liveRankItem : liveMessage.getRank()) {
            RealTimeBulletScreenMessage.RankItem rankItem = new RealTimeBulletScreenMessage.RankItem();
            rankItem.setNickname(liveRankItem.getNickname());
            rankItem.setAvatar(liveRankItem.getAvatar());
            // 设置排名
            if (liveRankItem.getRank() != null) {
                if (liveRankItem.getRank() instanceof String) {
                    rankItem.setRank((String) liveRankItem.getRank());
                } else {
                    rankItem.setRank(String.valueOf(liveRankItem.getRank()));
                }
            }
            rankItems.add(rankItem);
        }
        return rankItems;
    }

    // 将CastUser转换为UserProfile
    private UserProfile convertToUserProfile(LiveMessage.CastUser castUser) {
        if (castUser == null) {
            return null;
        }

        UserProfile userProfile = new UserProfile();
        userProfile.setUserId(castUser.getId());
        userProfile.setUserName(castUser.getName());
        userProfile.setUserAvatar(castUser.getAvatar());
        userProfile.setUserGender(castUser.getGender());
        userProfile.setUserShortId(castUser.getShortId());
        userProfile.setUserDisplayId(castUser.getDisplayId());
        userProfile.setUserSecUid(castUser.getSecUid());
        userProfile.setUserWebcastUid(castUser.getWebcastUid());

        // 设置用户等级
        if (castUser.getPayGrade() != null) {
            try {
                userProfile.setUserLevel(Integer.parseInt(castUser.getPayGrade().getLevel()));
            } catch (NumberFormatException e) {
                userProfile.setUserLevel(1);
            }
        } else {
            userProfile.setUserLevel(1);
        }

        // 设置粉丝团信息
        if (castUser.getFansClub() != null && castUser.getFansClub().getData() != null) {
            FansClubInfo fansClubInfo = new FansClubInfo();
            fansClubInfo.setLevel(castUser.getFansClub().getData().getLevel());
            fansClubInfo.setUserFansClubStatus(castUser.getFansClub().getData().getUserFansClubStatus());
            fansClubInfo.setAnchorId(castUser.getFansClub().getData().getAnchorId());

            // 设置徽章信息
            if (castUser.getFansClub().getData().getBadge() != null) {
                FansClubInfo.Badge badge = new FansClubInfo.Badge();
                
                // 转换徽章图标信息
                if (castUser.getFansClub().getData().getBadge().getIcons() != null) {
                    Map<String, FansClubInfo.Badge.BadgeIcon> convertedIcons = new java.util.HashMap<>();
                    
                    for (Map.Entry<String, LiveMessage.BadgeIcon> entry : 
                            castUser.getFansClub().getData().getBadge().getIcons().entrySet()) {
                        if (entry.getValue() != null) {
                            FansClubInfo.Badge.BadgeIcon badgeIcon = new FansClubInfo.Badge.BadgeIcon();
                            badgeIcon.setUrlList(entry.getValue().getUrlList());
                            badgeIcon.setUri(entry.getValue().getUri());
                            convertedIcons.put(entry.getKey(), badgeIcon);
                        }
                    }
                    
                    badge.setIcons(convertedIcons);
                }
                
                fansClubInfo.setBadge(badge);
            }

            userProfile.setFansClubInfo(fansClubInfo);
        }

        // 设置用户徽章
        if (castUser.getBadgeImageList() != null) {
            List<UserBadge> userBadges = new java.util.ArrayList<>();
            
            // 创建并添加徽章
            UserBadge userBadge = new UserBadge();
            userBadge.setUrlList(castUser.getBadgeImageList().getUrlList());
            userBadge.setImageType(castUser.getBadgeImageList().getImageType());
            
            // 设置徽章内容
            if (castUser.getBadgeImageList().getContent() != null) {
                UserBadge.BadgeContent badgeContent = new UserBadge.BadgeContent();
                badgeContent.setFontColor(castUser.getBadgeImageList().getContent().getFontColor());
                badgeContent.setLevel(castUser.getBadgeImageList().getContent().getLevel());
                badgeContent.setAlternativeText(castUser.getBadgeImageList().getContent().getAlternativeText());
                userBadge.setContent(badgeContent);
            }
            
            userBadges.add(userBadge);
            userProfile.setUserBadges(userBadges);
        }

        return userProfile;
    }
    
    // 将UserProfile信息设置到BulletScreenItem
    private void setUserProfileToItem(RealTimeBulletScreenMessage.BulletScreenItem item, UserProfile userProfile) {
        if (userProfile == null) {
            return;
        }
        
        item.setUserId(userProfile.getUserId());
        item.setUserName(userProfile.getUserName());
        item.setUserAvatar(userProfile.getUserAvatar());
        item.setUserGender(userProfile.getUserGender());
        item.setUserShortId(userProfile.getUserShortId());
        item.setUserDisplayId(userProfile.getUserDisplayId());
        item.setUserSecUid(userProfile.getUserSecUid());
        item.setUserWebcastUid(userProfile.getUserWebcastUid());
        item.setUserLevel(userProfile.getUserLevel());
        item.setUserBadges(userProfile.getUserBadges());
        item.setFansClubInfo(userProfile.getFansClubInfo());
    }
}